package server

import (
	"context"
	"errors"
	"fmt"
	"longmen/server/config/global"
	cache2 "longmen/server/internal/rpc/tencentim/cache"
	"longmen/server/internal/rpc/tencentim/messages/im"
	pvt_chat2 "longmen/server/internal/rpc/tencentim/pvt_chat"
	time2 "longmen/server/pkg/common/helper/timehelper"
	"longmen/server/pkg/common/helper/util"
	"longmen/server/pkg/common/report"
	"longmen/server/pkg/db/mysql/db_live"
	"longmen/server/pkg/db/mysql/db_main"
	"longmen/server/pkg/db/mysql/models/models_main"
	"longmen/server/pkg/db/redis/cache"
	pb "longmen/server/pkg/protobuf"
	"sort"
	"sync"
	"time"

	"github.com/spf13/cast"
)

/**
 * @author Jared
 * @description 我的-私聊记录页面
 * @createTime 15:09 2022/11/23
 **/
func (s *TencentIM) GetPrivateChatRecord(ctx context.Context, req *pb.PrivateChatRecordReq) (resp *pb.PrivateChatRecordResp, err error) {
	userIds := []string{}
	if req.UserId > 0 {
		userIds = append(userIds, cast.ToString(req.UserId))
	}
	hashUid := cast.ToString(util.HashUid(req.DeviceId))
	if hashUid != "" && cast.ToString(req.UserId) != hashUid {
		userIds = append(userIds, hashUid)
	}

	userChatSessions := []*im.Conversation{}
	chatSessions := []*im.Conversation{}
	for _, uid := range userIds {
		rs, err := pvt_chat2.GetSingleChatConversations(uid)
		if err != nil {
			continue
		}
		if len(rs) > 0 {
			userChatSessions = append(userChatSessions, rs...)
		}
	}
	mergeChatSessions := append(userChatSessions, db_main.DefaultChatAdmin()...)
	//global.Log.Debugf("mergeChatSessions len:%v,userIds:%v", len(mergeChatSessions), userIds)
	tmpChatSessions := map[string]bool{}
	for _, v := range mergeChatSessions {
		if tmpChatSessions[v.AnchorId] == false {
			tmpChatSessions[v.AnchorId] = true
			chatSessions = append(chatSessions, v)
		}
	}

	sort.Slice(chatSessions, func(i int, j int) bool {
		/*if chatSessions[i].AnchorId == global.Config.GetString("official.anchor1.uid") {
			return true
		}
		if chatSessions[i].AnchorId == global.Config.GetString("official.anchor2.uid") {
			return true
		}*/
		if chatSessions[i].LatestMsgTime > chatSessions[j].LatestMsgTime {
			return true
		}
		return false
	})
	var chatsGroup []*pb.ChatsGroup

	for _, v := range chatSessions {
		anchor, err := cache.GetUserFullInfo(cast.ToInt(v.AnchorId))
		if err != nil {
			cache2.DelConversationCache(v.AnchorId, v.ConversationId)
			cache2.DelConversationCache(v.UserId, v.ConversationId)
			continue
		}
		if v.LatestMsgTime == 0 {
			v.LatestMsgTime = time.Now().Unix() - 1800
		}

		if len(v.LastetMsgText) > 10 {
			textRune := []rune(v.LastetMsgText)
			v.LastetMsgText = string(textRune[0:12]) + "..."
		}

		chatsGroup = append(chatsGroup, &pb.ChatsGroup{
			AnchorId:     uint32(anchor.Id),
			AnchorAvatar: anchor.Avatar,
			AnchorName:   anchor.NickName,
			//LiveId:       uint64(liveId),
			//IsLiveOnline: isLiveOnline,
			ChatTime: time2.Stamp2Str(v.LatestMsgTime),
			//最近消息
			//ChatSessionId: uint32(v.ConversationId),
			LatestMsgTime: v.LatestMsgTime,
			LatestMsg:     v.LastetMsgText,
			FromWho:       cast.ToUint32(v.UserId),
			Status:        1,
		})
	}

	return &pb.PrivateChatRecordResp{
		ChatsGroup: chatsGroup,
	}, nil
}

/**
 * @author Jared
 * @description 我的-私聊记录页面-详情
 * @createTime 11:05 2022/11/22
 **/
func (s *TencentIM) GetPrivateChatRecordDetail(ctx context.Context, req *pb.PrivateChatRecordDetailReq) (resp *pb.PrivateChatRecordDetailResp, err error) {
	userIds := []string{}
	var userId string
	if len(req.DeviceId) > 0 {
		userIds = append(userIds, cast.ToString(util.HashUid(req.DeviceId)))
	}
	if req.UserId > 0 {
		userIds = append(userIds, cast.ToString(req.UserId))
	}
	conversationIds := []string{}
	for _, uid := range userIds {
		conversation, err := pvt_chat2.GetSingleChatConversationSendIdToRecvId(uid, cast.ToString(req.AnchorId))
		if err != nil {
			continue
		}
		conversationIds = append(conversationIds, conversation.ConversationId)
		userId = conversation.UserId
	}

	global.Log.Debugf("GetPrivateChatRecordDetail conversationIds:%v", conversationIds)
	history, _ := pvt_chat2.GetHistory(conversationIds, int(req.Page), int(req.Size))

	var msgGroup []*pb.SingleMsg
	for _, v := range history {
		global.Log.Debugf("GetPrivateChatRecordDetail history coentent:%s,img_url:%s", v.Content, v.ImgUrl)
		avatar, nickName := "", ""
		user, err := cache.GetUserFullInfo(cast.ToInt(v.SenderUid))
		if err == nil && user != nil {
			avatar = user.Avatar
			nickName = user.NickName
		}
		msgGroup = append(msgGroup, &pb.SingleMsg{
			Avatar:     avatar,
			NickName:   nickName,
			SessionId:  cast.ToString(v.SessionId),
			SenderUid:  cast.ToUint64(v.SenderUid),
			ReceiveUid: cast.ToUint64(v.ReceiveUid),
			Content:    v.Content,
			SendTime:   v.SendTime,
			ImgUrl:     v.ImgUrl,
			Id:         v.Id,
		})
	}

	for _, v := range userIds {
		cache.ReSetPrivateChatUnreadNum(cast.ToInt(req.AnchorId), cast.ToInt(v))
	}
	err = report.NewImReport().IncrBatchReadNum(userId)
	if err != nil {
		global.Log.Errorf("ImReport IncrBatchReadNum err:%v", err)
	}

	// 统计人数
	db_live.LiveOpenChatNum(int(req.AnchorId), int(req.UserId))

	//if len(msgGroup) <= 0 && req.Page == 1 {
	//	toUid := req.UserId
	//	if req.UserId <= 0 {
	//		toUid = uint64(util.HashUid(req.DeviceId))
	//	}
	//	sendAnchorWelcomeMsg(int(toUid), int(req.AnchorId))
	//}

	return &pb.PrivateChatRecordDetailResp{
		MsgGroup: msgGroup,
	}, nil
}

/**
 * @author Jared
 * @description 清空聊天记录
 * @createTime 15:39 2022/11/23
 **/
func (s *TencentIM) DeletePrivateChatRecord(ctx context.Context, req *pb.DeletePrivateChatRecordReq) (resp *pb.OperateSucceedResp, err error) {
	//resp = &pb.OperateSucceedResp{}
	//userIds := []uint64{}
	//if req.UserId > 0 {
	//	userIds = append(userIds, uint64(req.UserId))
	//}
	//if len(req.DeviceInfo) > 0 {
	//	userIds = append(userIds, uint64(util.HashUid(req.DeviceInfo)))
	//}
	//chatSessions, _ := db_main.GetPrivateChatSessionList(map[string]interface{}{
	//	"user_id": map[string]interface{}{
	//		"in": userIds,
	//	},
	//	"anchor_id": req.AnchorId,
	//}, "id desc", 0, 0, "")
	//
	//if len(chatSessions) <= 0 {
	//	return &pb.OperateSucceedResp{IsSucceed: true}, nil
	//}
	//
	//err = db_main.DeletePrivateChatSessions(chatSessions)
	//if err != nil {
	//	return
	//}
	//
	//var sessionIds []int
	//for _, v := range chatSessions {
	//	sessionIds = append(sessionIds, v.Id)
	//}
	//err = pvt_chat2.DelHistory(sessionIds)
	//if err != nil {
	//	return
	//}
	return &pb.OperateSucceedResp{IsSucceed: true}, nil
}

/**
 * @author Jared
 * @description 开始新的会话
 * @createTime 16:03 2022/11/23
 **/
func (s *TencentIM) StartChatSession(ctx context.Context, req *pb.StartChatSessionReq) (resp *pb.OperateSucceedResp, err error) {
	return &pb.OperateSucceedResp{IsSucceed: true}, nil
}

/**
 * @author Jared
 * @description 后台接入私聊会话
 * @createTime 15:49 2022/11/23
 **/
func (s *TencentIM) WiringChatSession(ctx context.Context, req *pb.WiringChatSessionReq) (resp *pb.OperateSucceedResp, err error) {
	//resp = &pb.OperateSucceedResp{}
	//chatSession, err := db_main.GetPrivateChatSession(map[string]interface{}{
	//	"id": req.ChatSessionId,
	//	"is_deleted": map[string]interface{}{
	//		"in": []int{0, 1},
	//	},
	//})
	//if err != nil {
	//	return nil, err
	//}
	//if chatSession.Id <= 0 {
	//	err = errors.New("会话不存在")
	//	return
	//}
	//
	//err = pvt_chat2.WiringChatSession(int(req.AdminId), chatSession)
	//if err != nil {
	//	return nil, err
	//}

	return &pb.OperateSucceedResp{IsSucceed: true}, nil
}

/**
 * @author Jared
 * @description 转让会话
 * @createTime 16:02 2022/11/23
 **/
func (s *TencentIM) TransChatSession(ctx context.Context, req *pb.TransChatSessionReq) (resp *pb.OperateSucceedResp, err error) {
	//resp = &pb.OperateSucceedResp{}
	//chatSession, err := db_main.GetPrivateChatSession(map[string]interface{}{
	//	"id": req.ChatSessionId,
	//})
	//if err != nil {
	//	return nil, err
	//}
	//if chatSession.Id <= 0 {
	//	err = errors.New("会话不存在")
	//	return
	//}
	//
	//if chatSession.Status != models_main.PrivateChatSessionStatusWiring {
	//	err = errors.New("会话未接入,无法转接")
	//	return
	//}
	//err = pvt_chat2.TransWait(chatSession)
	//if err != nil {
	//	return nil, err
	//}
	return &pb.OperateSucceedResp{IsSucceed: true}, nil
}

/**
 * @author Jared
 * @description 结束会话
 * @createTime 16:03 2022/11/23
 **/
func (s *TencentIM) EndChatSession(ctx context.Context, req *pb.EndChatSessionReq) (resp *pb.OperateSucceedResp, err error) {
	//resp = &pb.OperateSucceedResp{}
	//chatSession, err := db_main.GetPrivateChatSession(map[string]interface{}{
	//	"id": req.ChatSessionId,
	//})
	//if err != nil {
	//	return nil, err
	//}
	//if chatSession.Id <= 0 {
	//	err = errors.New("会话不存在")
	//	return
	//}
	//
	//err = pvt_chat2.EndChatSession(chatSession)
	//if err != nil {
	//	return nil, err
	//}
	return &pb.OperateSucceedResp{IsSucceed: true}, nil
}

/**
 * @author Jared
 * @description 后台发送消息
 * @createTime 23:24 2022/11/24
 **/
func (s *TencentIM) CustomReply(ctx context.Context, req *pb.CustomReplyReq) (resp *pb.OperateSucceedResp, err error) {
	global.Log.Debugf("CustomReply params:%v", req)
	resp = &pb.OperateSucceedResp{}
	conversation, err := pvt_chat2.GetSingleChatConversation(cast.ToString(req.GetAdminId()), req.GetSessionId())
	if err != nil || conversation.ConversationId == "" {
		err = errors.New("会话不存在")
		return
	}
	customerSendRequest := pvt_chat2.CustomerSendRequest{
		Content:  cast.ToString(req.GetContent()),
		SenderId: cast.ToString(req.GetAdminId()),
		UserId:   conversation.UserId,
		ImgUrl:   req.GetImgUrl(),
	}
	err = pvt_chat2.CustomReply(customerSendRequest, conversation)
	if customerSendRequest.Content == "admin_revoke" {
		return &pb.OperateSucceedResp{IsSucceed: err == nil}, err
	}
	if err == nil {
		err = cache.IncrPrivateChatUnreadNum(cast.ToInt(req.GetAdminId()), cast.ToInt(conversation.UserId))
		err = report.NewImReport().IncrBatchSendNum(conversation.UserId)
		if err != nil {
			global.Log.Errorf("ImReport IncrBatchSendNum err:%v", err)
		}
		if customerSendRequest.Content == "" && customerSendRequest.ImgUrl != "" {
			customerSendRequest.Content = "图片/视频消息..."
		}
		pvt_chat2.SetSingleChatConversationAnchorSend(conversation.UserId, cast.ToString(req.GetAdminId()), customerSendRequest.Content)

		//私聊统计
		userPrivateChatLog := &models_main.UserPrivateChatLog{}
		userPrivateChatLog.SenderUid = cast.ToInt(customerSendRequest.SenderId)
		userPrivateChatLog.ReceiveUid = cast.ToInt(customerSendRequest.UserId)
		userPrivateChatLog.SourceKey = conversation.Channel
		err = db_main.InsertStatPrivateChat(userPrivateChatLog)
		if err != nil {
			global.Log.Errorf("insert into stat private chat message error:%v", err)
		}
	}
	return &pb.OperateSucceedResp{IsSucceed: err == nil}, err
}

/**
 * @description 后台发送批量消息
 * @createTime 23:24 2022/11/24
 **/
func (s *TencentIM) BatchCustomReply(ctx context.Context, req *pb.BatchCustomReplyReq) (resp *pb.BatchCustomReplyResp, err error) {
	resp = &pb.BatchCustomReplyResp{}
	content := string(req.GetContent())

	var batchCustomUser []interface{}

	if req.GetAll() == 1 {
		err, batchCustomUser = pvt_chat2.NewOnlineDevice().GetAllOnlineDevice()
		global.Log.Debugf("走群发，在线总人数:%d,err:%v", len(batchCustomUser), err)
		if err != nil {
			return &pb.BatchCustomReplyResp{IsSucceed: false}, err
		}
	} else {
		for _, v := range req.GetUsers() {
			batchCustomUser = append(batchCustomUser, pvt_chat2.OnlineDeviceRequest{
				UserID:   v.GetUserId(),
				RoomID:   int(v.GetAnchorId()),
				Platform: int(v.GetPlatform()),
				Nickname: v.GetName(),
			})
		}
	}
	report.NewImReport().IncrBatchEveryTimeSendNum(int64(len(batchCustomUser)))
	//分割
	maxNum := 500
	f := util.NewSplitter(maxNum, batchCustomUser)
	wg := sync.WaitGroup{}
	getSplitResult := f.GetSplitResult()
	wg.Add(len(getSplitResult))
	for _, item := range getSplitResult {
		batchCustomerSendRequest := make(map[int][]*pvt_chat2.BatchCustomerSendRequest)
		for _, v := range item.Item {
			onlineDevice, ok := v.(pvt_chat2.OnlineDeviceRequest)
			global.Log.Debugf("OnlineDeviceRequest:%+v,onlineDevice:%+v,ok:%v", v, onlineDevice, ok)
			if !ok {
				global.Log.Errorf("onlineDevice decode err")
				continue
			}
			anchorId := onlineDevice.RoomID
			_, err = cache.GetUserFullInfo(anchorId)
			if err != nil {
				global.Log.Errorf("GetUserFullInfo err:%v", err)
				continue
			}
			session, err := pvt_chat2.SetSingleChatConversationAnchorSend(onlineDevice.UserID, cast.ToString(anchorId), string(req.GetContent()))
			if err != nil {
				global.Log.Errorf("create session err:%v", err)
				continue
			}
			cache.IncrPrivateChatUnreadNum(anchorId, cast.ToInt(onlineDevice.UserID))
			err = report.NewImReport().IncrBatchSendNum(onlineDevice.UserID)
			if err != nil {
				global.Log.Errorf("ImReport IncrBatchSendNum err:%v", err)
			}
			batchCustomerSendRequest[anchorId] = append(batchCustomerSendRequest[anchorId], &pvt_chat2.BatchCustomerSendRequest{
				UserId:   cast.ToInt(onlineDevice.UserID),
				Session:  session,
				AnchorId: anchorId,
			})
		}
		err = pvt_chat2.BatchCustomReply(content, batchCustomerSendRequest)
	}
	return &pb.BatchCustomReplyResp{IsSucceed: err == nil}, err
}

func sendAnchorWelcomeMsg(userId, anchorId int) {
	user, _ := cache.GetUserFullInfo(cast.ToInt(userId))
	nick := ""
	if user != nil && user.Id > 0 {
		nick = user.NickName
	} else {
		userIdStr := cast.ToString(userId)
		if len(userIdStr) >= 10 {
			nick = global.Lang.T("anonymous") + userIdStr[len(userIdStr)-9:]
		}
	}
	content := fmt.Sprintf("嗨, %s ! 很高兴为您服务, 随时告诉我需要什么服务哦~", nick)
	conversation, err := pvt_chat2.SetSingleChatConversationAnchorSend(cast.ToString(userId), cast.ToString(anchorId), content)
	if err != nil || conversation.ConversationId == "" {
		global.Log.Errorf("sendAnchorWelcomeMsg conversation err:%v", err)
		return
	}

	customerSendRequest := pvt_chat2.CustomerSendRequest{
		Content:  content,
		SenderId: cast.ToString(anchorId),
		UserId:   conversation.UserId,
		ImgUrl:   "",
	}
	err = pvt_chat2.CustomReply(customerSendRequest, conversation)
	if err != nil {
		global.Log.Errorf("sendAnchorWelcomeMsg CustomReply err:%v", err)
		return
	}
}
